<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="wtaskName">
        <el-input
          v-model="queryParams.wtaskName"
          placeholder="请输入任务编号/名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="wtaskWoCode">
        <el-input
          v-model="queryParams.wtaskWoCode"
          placeholder="请输入工单名称/编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="wtaskStatus">
        <el-select
          v-model="queryParams.wtaskStatus"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in getTaskStatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="wtaskRouteCode">
        <el-select
          v-model="queryParams.wtaskRouteCode"
          placeholder="请选择工艺路线"
          clearable
        >
          <el-option
            v-for="r in pbsProcedureRoutes"
            :key="r.prouteCode"
            :label="r.prouteName"
            :value="r.prouteCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="wtaskProcedureCode">
        <el-select
          v-model="queryParams.wtaskProcedureCode"
          placeholder="请选择工序"
          clearable
        >
          <el-option
            v-for="r in pbsProcedures"
            :key="r.procedureCode"
            :label="r.procedureName"
            :value="r.procedureCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="wtaskCell">
        <el-select
          v-model="queryParams.wtaskCell"
          placeholder="请选择生产单元"
          clearable
        >
          <el-option
            v-for="r in pbsWorkCells"
            :key="r.procedureCode"
            :label="r.workCellName"
            :value="r.workCellCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="wtaskStart">
        <el-date-picker clearable
                        v-model="queryParams.wtaskStart"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择开工时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="wtaskEnd">
        <el-date-picker clearable
                        v-model="queryParams.wtaskEnd"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择完工时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pro:workTask:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column type="index" label="序号" align="center" width="120" fixed show-overflow-tooltip />
      <el-table-column label="任务编号" align="center" prop="wtaskCode" width="150" fixed show-overflow-tooltip />
      <el-table-column label="任务名称" align="center" prop="wtaskName" width="120" fixed show-overflow-tooltip />
      <el-table-column label="生产单元" align="center" prop="workCellName" width="120" fixed show-overflow-tooltip />
      <el-table-column label="工单编号" align="center" prop="wtaskWoCode" width="150" show-overflow-tooltip />
      <el-table-column label="工单名称" align="center" prop="workOrderName" width="100" show-overflow-tooltip />
      <el-table-column label="工艺路线" align="center" prop="prouteName" width="100" show-overflow-tooltip />
      <el-table-column label="工序" align="center" prop="procedureName" width="100" show-overflow-tooltip />
      <el-table-column label="计划数量" align="center" prop="wtaskNum" />
      <el-table-column label="计划开工时间" align="center" prop="wtaskStart" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wtaskStart) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划完工时间" align="center" prop="wtaskEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wtaskEnd) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划生产时长" align="center" width="180">
        <template slot-scope="scope">
          <span>{{ getHours(scope.row.wtaskEnd, scope.row.wtaskStart) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际开工时间" align="center" prop="wtaskRStart" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wtaskRStart) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际完工时间" align="center" prop="wtaskREnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wtaskREnd) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际生产时长" align="center" width="180">
        <template slot-scope="scope">
          <span>{{ getHours(scope.row.wtaskREnd, scope.row.wtaskRStart) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="wtaskStatus" fixed="right">
        <template slot-scope="scope">
          <dict-tag :options="getTaskStatus" :value="scope.row.wtaskStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleDetail(scope.row)"
            v-hasPermi="['pro:workTask:query']"
          >查看
          </el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
                       v-hasPermi="['pro:schedule:edit']"
                       v-if="scope.row.wtaskStatus === '0' || scope.row.wtaskStatus === '1' || scope.row.wtaskStatus === '2' || scope.row.wtaskStatus === '5'"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleArrangePeo" icon="el-icon-edit"
                                v-hasPermi="['pro:schedule:edit']"
                                v-if="scope.row.wtaskStatus === '0'"
              >派工
              </el-dropdown-item>
              <el-dropdown-item command="handleStartTask" icon="el-icon-edit"
                                v-hasPermi="['pro:schedule:edit']"
                                v-if="scope.row.wtaskStatus === '1'"
              >开工
              </el-dropdown-item>
              <el-dropdown-item command="handleReportTask" icon="el-icon-edit"
                                v-hasPermi="['pro:workTask:edit']"
                                v-if="scope.row.wtaskStatus === '2' || scope.row.wtaskStatus === '5'"
              >报工
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--    报工 dialog-->
    <el-dialog title="报工" :visible.sync="reportVisibleDialog">
      <el-form :model="currentWorkTask" label-width="90px" label-position="left" size="small">
        <el-form-item label="工单任务">
          <span>{{ currentWorkTask.wtaskName }}</span>
        </el-form-item>
        <el-form-item label="任务编号">
          <span>{{ currentWorkTask.wtaskCode }}</span>
        </el-form-item>
        <el-form-item label="工艺路线">
          <span>{{ currentWorkTask.prouteName }}</span>
        </el-form-item>
        <el-form-item label="工艺路线编号">
          <span>{{ currentWorkTask.wtaskRouteCode }}</span>
        </el-form-item>
        <el-form-item label="工序">
          <span>{{ currentWorkTask.procedureName }}</span>
        </el-form-item>
        <el-form-item label="工序编号">
          <span>{{ currentWorkTask.wtaskProcedureCode }}</span>
        </el-form-item>
        <el-form-item label="任务数量">
          <span>{{ currentWorkTask.wtaskNum }}</span>
        </el-form-item>
        <el-form-item label="报工数量">
          <el-input-number v-model="currentWorkTask.reportCompleteNum" :min="1" :max="currentWorkTask.wtaskNum" />
        </el-form-item>
        <el-form-item label="报工人员">
          <el-select v-model="currentWorkTask.reportPeoCode" placeholder="请选择报工人员">
            <el-option
              v-for="item in workOrderPeo"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报工时间">
          <el-date-picker clearable
                          v-model="currentWorkTask.reportTime"
                          type="datetime"
                          value-format="yyyy-MM-dd hh:mm:ss"
                          placeholder="请选择报工时间"
          />
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="closeReport" size="small">取 消</el-button>
        <el-button type="primary" @click="okReport" size="small">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { conditionWorkTask, getUser, listWorkTask, startWork } from '@/api/yyj/pro/workTask'
import { addProWorkReport } from '@/api/yyj/pro/workReport'
import { calcHours } from '@/utils/yyj'
import { formatDate } from '@/utils'

export default {
  name: 'WorkTask',
  dicts: ['pro_task_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单任务表格数据
      workTaskList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wtaskQcPeo: null,
        wtaskWoCode: null,
        wtaskName: null,
        wtaskManager: null,
        wtaskGroup: null,
        wtaskCell: null,
        wtaskNum: null,
        wtaskRNum: null,
        wtaskStart: null,
        wtaskEnd: null,
        wtaskRStart: null,
        wtaskREnd: null,
        wtaskBom: null,
        wtaskBomVersion: null,
        wtaskProcedureCode: null,
        wtaskRouteCode: null,
        wtaskStatus: null,
        wtaskPCloseReason: null,
        wtaskPDesc: null
      },
      pbsProcedureRoutes: [],
      pbsProcedures: [],
      pbsWorkCells: [],
      reportVisibleDialog: false,
      currentWorkTask: {},
      // 当前工单被派工的人员
      workOrderPeo: []
    }
  },
  computed: {
    getTaskStatus() {
      return this.dict.type.pro_task_status
    }
  },
  created() {
    Promise.all([this.getList(), this.getCondition()])
  },
  methods: {
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleArrangePeo':
          this.handleArrangePeo(row)
          break
        case 'handleStartTask':
          this.handleStartTask(row)
          break
        case 'handleReportTask':
          this.handleReportTask(row)
          break
        default:
          break
      }
    },
    // 获取时长
    getHours(end, start) {
      if (!end || !start) {
        return ''
      }
      return calcHours(end, start) + '小时'
    },
    // 查看详情
    handleDetail(row) {
      this.$router.push({
        path: `/pro/task-detail/${row.wtaskCode}`
      })
    },
    /** 查询工单任务列表 */
    async getList() {
      this.loading = true
      const res = await listWorkTask(this.queryParams)
      this.workTaskList = res.rows
      this.total = res.total
      this.loading = false
    },
    // 获取工单任务的条件内容
    async getCondition() {
      const res = await conditionWorkTask()
      this.pbsProcedureRoutes = res.pbsProcedureRoutes
      this.pbsProcedures = res.pbsProcedures
      this.pbsWorkCells = res.pbsWorkCells
    },
    // 派工
    handleArrangePeo(row) {
      this.$router.push({
        path: `/pro/task-change/${row.wtaskCode}`
      })
    },
    // 开工
    handleStartTask(row) {
      startWork({
        proWorkTask: {
          wtaskCode: row.wtaskCode,
          wtaskRStart: formatDate(new Date()),
          wtaskStatus: '2',
          wtaskWoCode: row.wtaskWoCode
        }
      }).then(_ => {
        this.$modal.msgSuccess('已开工')
        this.getList()
      }).catch(_ => {
        this.$modal.msgWarning('该工单上一道任务还未完成')
      })
    },
    // 报工
    async handleReportTask(row) {
      console.log('row ', row)
      this.currentWorkTask = { ...row }
      this.currentWorkTask.reportCompleteNum = 1
      const res = await getUser(this.currentWorkTask.wtaskCode)
      this.workOrderPeo = res.data
      this.reportVisibleDialog = true
    },
    // 关闭报工
    closeReport() {
      this.reportVisibleDialog = false
    },
    // 确认报工
    async okReport() {
      // 生成报工单
      this.$modal.loading('正在报工...')
      const postData = {
        reportCompleteNum: this.currentWorkTask.reportCompleteNum,
        reportPeoCode: this.currentWorkTask.reportPeoCode,
        reportOCode: this.currentWorkTask.wtaskWoCode,
        reportOCodeName: this.currentWorkTask.workOrderName,
        reportBom: this.currentWorkTask.wtaskBom,
        reportBomVersion: this.currentWorkTask.wtaskBomVersion,
        reportTCode: this.currentWorkTask.wtaskCode,
        reportTCodeName: this.currentWorkTask.wtaskName,
        reportWCellName: this.currentWorkTask.workCellName,
        reportWCell: this.currentWorkTask.wtaskCell,
        reportRouteName: this.currentWorkTask.prouteName,
        reportRoute: this.currentWorkTask.wtaskRouteCode,
        reportProcedureName: this.currentWorkTask.procedureName,
        reportProcedure: this.currentWorkTask.wtaskProcedureCode,
        reportGroupName: this.currentWorkTask.wtaskGroupName,
        reportGroup: this.currentWorkTask.wtaskGroup,
        reportWManager: this.currentWorkTask.wtaskManager,
        reportTime: this.currentWorkTask.reportTime,
        reportQcPeo: this.currentWorkTask.wtaskQcPeo,
        reportCalcSalType: this.currentWorkTask.wtaskCalcType,
        reportCalcSalSingle: this.currentWorkTask.wtaskCalcSingle,
        reportCalcSalTime: calcHours(this.currentWorkTask.reportTime, this.currentWorkTask.wtaskRStart)
      }
      await addProWorkReport(postData)
      this.$modal.closeLoading()
      this.$modal.msgSuccess('报工成功!')
      await this.$tab.refreshPage()
      // this.reportVisibleDialog = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.wtaskCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pro/workTask/export', {
        ...this.queryParams
      }, `workTask_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped lang="scss">
.el-dialog {
  .el-form {
    display: flex;
    flex-wrap: wrap;
    width: 100%;

    .el-form-item {
      width: 50%;
      padding-left: 10%;
      margin-right: 0 !important;
      white-space: nowrap;
    }

    .el-input-number {
      width: 150px;
    }
  }
}
</style>
